package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping
    public Result saveDishAndFlavors(@RequestBody DishDTO dishDTO) {
        log.info("新增菜品");
        cleanCache(dishDTO.getCategoryId().toString());
        dishService.saveWithFlavors(dishDTO);
        return Result.success();
    }
    @GetMapping("/page")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询");
        return Result.success(dishService.pageQuery(dishPageQueryDTO));
    }
    @DeleteMapping
    public Result deleteDish(@RequestParam("ids") List<Long> ids) {
        log.info("删除菜品");
        cleanCache("dish_*");
        dishService.deleteByIds(ids);
        return Result.success();
    }
    @PutMapping
    public Result updateDish(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品");
        cleanCache("dish_*");
        dishService.update(dishDTO);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result<DishDTO> getById(@PathVariable Long id) {
        log.info("根据id查询菜品");
        DishDTO dishDTO = dishService.getById(id);
        return Result.success(dishDTO);
    }
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status, Long id) {
        log.info("起售停售");
        cleanCache("dish_*");
        dishService.startOrStop(status, id);
        return Result.success();
    }
    @GetMapping("/list")
    public Result<List<Dish>> list(Long categoryId) {
        log.info("根据分类id查询菜品");
        List<Dish> dishDTOList = dishService.list(categoryId);
        return Result.success(dishDTOList);
    }
    private void cleanCache(String pattern) {
        Set<String> keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
